<template>
  <div v-if="show" class="modal-overlay" @click.self="emits('close')">
    <div class="modal">
      <h3>学生注册</h3>
      <form @submit.prevent="submitForm">
        <p>
          <label>姓名：</label>
          <input v-model="form.name" type="text" required />
        </p>
        <p>
          <label>年龄：</label>
          <input v-model="form.age" type="number" required />
        </p>
        <p>
          <label>性别：</label>
          <label><input type="radio" value="男" v-model="form.gender" /> 男</label>
          <label><input type="radio" value="女" v-model="form.gender" /> 女</label>
        </p>
        <p>
          <label>照片：</label>
          <input type="file" @change="handleFileChange" required />
        </p>
        <div class="actions">
          <button type="submit">提交</button>
          <button type="button" @click="emits('close')">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import axios from 'axios'

// 直接声明 props，不赋值给变量
defineProps({
  show: Boolean
})

// 定义 emits
const emits = defineEmits(['close', 'success'])

const form = reactive({
  name: '',
  age: '',
  gender: '男',
  photofile: null
})

// 处理文件选择
const handleFileChange = (e) => {
  form.photofile = e.target.files[0]
}

// 提交表单
const submitForm = async () => {
  try {
    const url = 'http://localhost:8080/student/add'
    const formData = new FormData()
    formData.append('name', form.name)
    formData.append('age', form.age)
    formData.append('gender', form.gender)
    formData.append('photofile', form.photofile)

    const res = await axios.post(url, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    if (res.data.code === 1) {
      alert('注册成功')
      emits('success') // 通知父组件刷新学生列表
      emits('close') // 关闭模态框
    } else {
      alert('注册失败: ' + res.data.msg)
    }
  } catch (err) {
    console.error('提交失败:', err)
    alert('提交出错，请检查服务器')
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.modal {
  background: white;
  padding: 20px;
  border-radius: 6px;
  min-width: 320px;
}
.actions {
  margin-top: 12px;
}
.actions button {
  margin-right: 8px;
}
</style>
